import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pojo/vo/UserVo.dart';
import 'package:word_range_client/repositories/UserRepository.dart';

import '../pojo/Result.dart';
import '../pojo/dto/UserDto.dart';


class UserViewModel {
  UserViewModel() {
    initializeCurrentUser();
  }
  UserVo? _currentUser;

  UserVo? get currentUser => _currentUser;

  Future<void> initializeCurrentUser() async {
    _currentUser = await _fetchCurrentUserFromLocalStorage();
  }

  Future<UserVo?> _fetchCurrentUserFromLocalStorage() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString("currentUser");
    if (userJson != null) {
      return UserVo.fromJson(json.decode(userJson));
    }
    return null;
  }

  Future<UserVo?> saveCurrentUserToLocalStorage(String userVoJson) async {
    final prefs = await SharedPreferences.getInstance();
    if (userVoJson != '') {
      prefs.setString("currentUser", userVoJson);
    }
    return null;
  }

  Future<Result> login(String phone, String password) async{
    final prefs = await SharedPreferences.getInstance();
    prefs.remove("token");
    Result result = await UserRepository.login(phone, password);
    if(result.code == 1){  // 登录成功
      // 保存登录凭据
      String token = result.data!["token"];
      prefs.setString("token", token);
      prefs.setString("phone", phone);
      prefs.setString("password", password);

      // 在本地保存缓存中的用户信息
      Result re = await UserRepository.getUserByToken(token);
      if(re.code == 1){
        saveCurrentUserToLocalStorage(json.encode(re.data!));
      }else{
        throw Exception("从缓存获取登录信息失败，请重试");
      }

    }
    return result;
  }

  Future<Result> register(String name, String phone, String password) async{
    Result result = await UserRepository.register(name, phone, password);
    return result;
  }


  Future<Result> getRegisterDays() async{
    Result result = await UserRepository.getRegisterDays();
    return result;
  }

  Future<Result> updateUser(UserDto userDto) async {
    Result result = await UserRepository.updateUser(userDto);
    if(result.code == 1){
      final prefs = await SharedPreferences.getInstance();
      final userJson = prefs.getString("currentUser");
      if (userJson != null) {
        UserVo user = UserVo.fromJson(json.decode(userJson));
        user.name = userDto.name;
        user.signature = userDto.signature;
        saveCurrentUserToLocalStorage(json.encode(user));
      }
    }
    return result;
  }

  Future<Result> deleteUser() async {
    Result result = await UserRepository.deleteUser();
    if(result.code == 1){
      final prefs = await SharedPreferences.getInstance();
      prefs.clear();
    }
    return result;
  }

  Future<Result> getUserActivityIntegral() async {
    Result result = await UserRepository.getUserActivityIntegral();
    return result;
  }



}
